<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            position: relative;
            width: 300px;
            height: 300px;
            margin: 50px auto;
            background-color: pink;
        }

        .box>.son {
            position: absolute;
            top: 0;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: skyblue;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="son"></div>
    </div>
</body>
<script>
    // 获取元素
    const box = document.querySelector('.box');
    const son = document.querySelector('.son');

    // 初始化小盒子位置
    son.style.left = `${box.clientWidth / 2 - son.offsetWidth / 2}px`;
    son.style.top = `${box.clientHeight / 2 - son.offsetHeight / 2}px`;

    // 注册事件
    // 鼠标按下
    son.addEventListener('mousedown', function (e) {
        // 按下位置
        let x = e.pageX - son.offsetLeft;
        let y = e.pageY - son.offsetTop;

        // 鼠标拖动
        box.addEventListener('mousemove', moveSon);
        document.addEventListener('mouseup', function () {
            box.removeEventListener('mousemove', moveSon);
        });

        // 移动小盒子
        function moveSon(e) {
            // 移动距离
            let posX = e.pageX - x;
            let posY = e.pageY - y;

            // 确定边界
            if (posX < 0) posX = 0;
            if (posX > box.clientWidth - son.offsetWidth) posX = box.clientWidth - son.offsetWidth;
            if (posY < 0) posY = 0;
            if (posY > box.clientHeight - son.offsetHeight) posY = box.clientHeight - son.offsetHeight;

            // 移动位置
            son.style.left = `${posX}px`;
            son.style.top = `${posY}px`;
        }
    });
</script>

</html>